<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/27
 * Time: 16:56
 */

namespace app\api\controller;

use app\callback\Pay;
use app\Request;
use think\facade\Db;

use think\facade\Config;
class Aliyun
{
    /**
     * @var string
     * https://docs.open.alipay.com/309/106237/
     */
//    public $appid = '2018093061534902';
//    public $appid;
//    public $public_key;
//    public $private_key;
//    public $notify_url;
//    public $appCertPath;
//    public $alipayCertPath;
//    public $rootCertPath;

    //public $rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDa18/7+WGpRtrwyYS9dYtUX+/rIqGWvaJwxghCgsYm1C61y+NPBM8NzSqeWj9LkEdPMpK2eEImhkoPiBaCdk5EPVmgBJdJLHLtBqoJ9rdaPCs0eaHDYH0wC02FyzcLIbaVx8ExVchlNHWkLy1FdMG3glcYub04cO5B7fiBEngwjaQThxzW6WkCJ2AZbEouPoZIZBaWQ3UVF9dOXRg/ft1n1HWB6uhV37kAIIvck99QyQqTJOciXBzyJxABB/Op6a25Jn5SfxOfT/6UodXajvL8K6Ntb9Ut/MDcO7yw0dACG4HnX6Jtx3SUql1PHtGLmLm4R2uX7ElHjSJrx/WQelRHAgMBAAECggEAVQiQZy8idHz0q6UR7/ARgGp6tdnSAdmTmdBI+1cHGaVOtRMRMu4CajFzQu58M6dPHgXfngkiYwfBFUHixTSk+rz/6z59blBYI6N4RMDZw7UncI9mfJ0sZ5OsvrUUoT2rTY29kqbrY++7Wl1+cMOKVfzOTOw3CwxOd824xqZfjzVx2FoXXXaIk4ujJpa1+LWQl8o+V7s9wHdrwm1nHSvZ/hbvn88AOlfCqMayTofeEtEBKCqkG9ctVJerSmb3tUN13k1Z2QN1iOU67eQwousUSnvcvJViY/4iqzKzzXD4bRPOs0MUp3//V2kmHLclkzut1OjP2h2oGqEycNa1X42XMQKBgQD85RbgX/7/sMxxCiGXtFmPIx3L/aJ+oreh6XJXEiBjIn/iuOecegk7HNEkCcR34T5q5TTz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XJXEiBjIn/iuOecegk7HNEkCcR34T5q5TTzWPRueY2NQsOKeP53Xa88rM8RbA5eLkRlUV4jkvgZiws0jdXRaSTxfNbcTZ+sQHtWEe+a9GTQZEEG25ZJnjaAvRBAS2umzvkFQW9YLwKBgQDdh7CRei8VSKrRcPff86avF5LvKg9R3zAaRc+04GngR4M45MsKDu1poC7Apk3BGgoyXw2n+2+clDxCmB+doqWYCOXy26tMW5TTurVl7ctFzLRbEB9+PZEjh+e0l6XsxyuA0FeymiUrX4FXLObqvibMix2lnEjRCXfWaTb8OqAnaQKBgCtLvULkrG9yAU5JAb9LLRoIVQ2berpbeTzLDrxBajIOsf5K0bxEWFg6csPMuEod0eXTH+GZlR9kyAsrJvcKB+a/r0SgAUNmUH9nRGZkK83DV55n4583uSeE7MI7MT2+PFvtHjB6GZ9Zv/i9cTSPW4d3ArW/qIyZXPDN9mwj68AZAoGBAKhPzN5rB9TS9j3U5++2jmEftxqRSTx6J3D+s5YIn0iw7MlQQ9ericQj2QG0GQVrBG5K+/QyPBWqJrKuI+8/wTLnJ9bCAb8tIcFQbTw5VKT+p9U8RcFDg7+MJYZ3ZbCljq77HHZtWWo/0ORsEDIwMQhddjP6rvRrjipQnF89J6tpAoGBAOoPy2l3yMYYwot/TECjMBGoT/cmlNwVG1Sc9nK2tq1z92ei2k608XG70eM8IPi7vyks1w7SQQO375xJrs5Axnatg9U7MfyKJKJksS2RGByW03tuBilbBgNKjcosJh1ocsw6onTeajdsuijclDkxqmdbEk57OeBCER8T9vXMsWQI";
   // public $rsaPrivateKey =  config('alipay')['pay']['private_key'];
    //    public $notifyurl = Request::instance()->domain();//不允许

//    public function __construct()
//    {
//        $this->appid = Config::get('aliyun.pay.appid');
//        $this->public_key = Config::get('aliyun.pay.public_key');
//        $this->private_key = Config::get('aliyun.pay.private_key');
//        $this->appCertPath = public_path() . "cert/alipay/appCertPublicKey_2021002193603027.crt";
//        $this->alipayCertPath = public_path() . "cert/alipay/alipayCertPublicKey_RSA2.crt";
//        $this->rootCertPath = public_path() . "cert/alipay/alipayRootCert.crt";
//        $this->notify_url = url('notifyurl',[],'false',true);
//    }
    public function app_recharge(Request $request){
        $notifyurl = url('Wechat/notifyurl', [], false, true);
        $order_number = order_number();
        $score = \app\model\MemberScore::where('id', $request->id)->value('score');
        $send_score = \app\model\MemberScore::where('id', $request->id)->value('send_score');
        $price = $score + $send_score;
        Db::name('unifiedorder')->insert(['member_id' => $request->member_id, 'pay_type' => '支付宝', 'pay_action' => '充值', 'price' => $score,'send_score'=>$price, 'order_number' => $order_number, 'status' => 1, 'create_time' => date('Y-m-d H:i:s')]);
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopClient.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/request/AlipayFundTransUniTransferRequest.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopCertClient.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopCertification.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AlipayConfig.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/request/AlipayTradeAppPayRequest.php';
        $aop = new \AopCertClient;
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $config = config('aliyun.pay');
        $aop->appId = $config['appid'];
        /** 密钥格式为pkcs1，如何获取私钥请参考：https://opensupport.alipay.com/support/helpcenter/207/201602469554  **/
        $aop->rsaPrivateKey = $config['private_key'];
        /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
        $appCertPath = $config['app_cert_path'];
        /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
        $alipayCertPath = $config['alipay_cert_path'];
        /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
        $rootCertPath = $config['root_cert_path'];
        $aop->format = "json";
        $aop->charset= "GBK";
        $aop->signType= "RSA2";
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.open.public.template.message.industry.modify
        $request = new \AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        //此次只是参数展示，未进行字符串转义，实际情况下请转义
        $pay_amount = config('app.pay_amount');
        $total_amount = $pay_amount == 0 ? $price : $pay_amount;
        $object = new \stdClass();
        $object->out_trade_no = $order_number;
        $object->total_amount = $total_amount;
        $object->subject = '充值送积分';
        $object->product_code ='QUICK_MSECURITY_PAY';
        $object->body = '充值';
//        $object->time_expire = '2022-08-01 22:00:00';
//        $object->body = '充值body';
        $json = json_encode($object);
        $request->setBizContent($json);
        $request->setNotifyUrl($config['notify_url']);

        $response= $aop->sdkExecute($request);
        //$data = $data = str_replace( '&timestamp' , '&amp;timestamp' , $response);
        return ['code' => 200, 'msg' => '支付宝下单参数', 'data' =>$response];
        print_r(htmlspecialchars($response));die;
    }




    /**
     * 支付宝回调
     * 进来直接改成2 防止数据异常 重新调用
     */
    public function notifyurl(Request $request)
    {
        $param = $request->param();
        $status = Db::name('unifiedorder')->where('order_number',$param['out_trade_no'])->value('status');
        if($status != 1){ die;} //只有待支付才可以
        paylog('========== aliyun start ==========','alipay');
        Db::name('unifiedorder')->where('order_number',$param['out_trade_no'])->where('status',1)->update(['status'=>2]);

        try {
            //require_once ROOT_PATH . 'extend/alipay-sdk-PHP-3.3.2/AopSdk.php';
            require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopClient.php';
            require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/request/AlipayFundTransUniTransferRequest.php';
            require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopCertClient.php';
            require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopCertification.php';
            require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AlipayConfig.php';
            require_once root_path() . 'extend/alipay-sdk-php-all-master/aop//request/AlipayTradeAppPayRequest.php';
            paylog($param,'alipay');
            $aop = new \AopCertClient;
            /** 支付宝网关 **/
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            /** 应用id,如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
            $config = config('aliyun.pay');
            $aop->appId = $config['appid'];
            /** 密钥格式为pkcs1，如何获取私钥请参考：https://opensupport.alipay.com/support/helpcenter/207/201602469554  **/
            $aop->rsaPrivateKey = $config['private_key'];
            /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
            $appCertPath = $config['app_cert_path'];
            /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
            $alipayCertPath = $config['alipay_cert_path'];
            /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
            $rootCertPath = $config['root_cert_path'];
            /** 设置签名类型 **/
            $aop->signType= "RSA2";
            /** 设置请求格式，固定值json **/
            $aop->format = "json";
            /** 设置编码格式 **/
            $aop->charset= "utf-8";
            /** 调用getPublicKey从支付宝公钥证书中提取公钥 **/
            $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
            /** 是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内 **/
            $aop->isCheckAlipayPublicCert = true;
            /** 调用getCertSN获取证书序列号 **/
            $aop->appCertSN = $aop->getCertSN($appCertPath);
            /** 调用getRootCertSN获取支付宝根证书序列号 **/
            $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
            /** 实例化具体API对应的request类，类名称和接口名称对应，当前调用接口名称：alipay.trade.app.pay **/
            $flag = $aop->rsaCheckV1($param, $alipayCertPath, "RSA2");
            paylog($flag,'alipay');
            if ($flag) {
                $param['pay_action'] = $param['body']; //支付方式
                $param['pay_type'] = '支付宝'; //支付类型
                (new Pay())->business_logic($param);
                paylog('========== aliyun end ==========','alipay');
            }else{
                paylog('签名错误','alipay');
            }

        } catch (\Exception $e) {
            paylog($e->getMessage(),'alipay');
        }

    }

    /*
     * 支付宝提现
     */
    public function withdraw($order_number,$brokerage,$withdraw_no,$name='')
    {

        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopClient.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/request/AlipayFundTransUniTransferRequest.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopCertClient.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AopCertification.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/AlipayConfig.php';
        require_once root_path() . 'extend/alipay-sdk-php-all-master/aop/request/AlipayFundTransUniTransferRequest.php';
        /** 初始化 **/
        $aop = new \AopCertClient;
        /** 支付宝网关 **/
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        /** 应用id,如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
        $config = config('aliyun.pay');
        $aop->appId = $config['appid'];
        /** 密钥格式为pkcs1，如何获取私钥请参考：https://opensupport.alipay.com/support/helpcenter/207/201602469554  **/
        $aop->rsaPrivateKey = $config['private_key'];
        /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
        $appCertPath = $config['app_cert_path'];
        /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
        $alipayCertPath = $config['alipay_cert_path'];
        /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
        $rootCertPath = $config['root_cert_path'];
        /** 设置签名类型 **/
        $aop->signType = "RSA2";
        /** 设置请求格式，固定值json **/
        $aop->format = "json";
        /** 设置编码格式 **/
        $aop->charset = "utf-8";
        /** 调用getPublicKey从支付宝公钥证书中提取公钥 **/
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
//        var_dump($config['private_key']);
//        var_dump($aop->alipayrsaPublicKey);die;
        /** 是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内 **/
        $aop->isCheckAlipayPublicCert = true;
        /** 调用getCertSN获取证书序列号 **/
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        /** 调用getRootCertSN获取支付宝根证书序列号 **/
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
        /** 实例化具体API对应的request类，类名称和接口名称对应,当前调用接口名称：alipay.fund.trans.uni.transfer(单笔转账接口) **/
        $request = new \AlipayFundTransUniTransferRequest ();
        /** 设置业务参数，具体接口参数传值以文档说明为准：https://opendocs.alipay.com/apis/api_28/alipay.fund.trans.uni.transfer/ **/
        $object = new \stdClass();
        $object->out_biz_no = $order_number;
        $object->trans_amount = $brokerage;
        $object->product_code = 'TRANS_ACCOUNT_NO_PWD';
        $object->biz_scene = 'DIRECT_TRANSFER';
        $object->payee_info = new \stdClass();
        $object->payee_info->identity = $withdraw_no;
        $object->payee_info->identity_type ='ALIPAY_LOGON_ID';
        $object->payee_info->name = $name;
        $object->remark = '单笔转账';
        $json = json_encode($object);
        $request->setBizContent($json);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode;

        if(!empty($resultCode)&&$resultCode->code == 10000){
            return (['code' =>200,'msg'=>$resultCode->msg]);
        } else {
            return (['code' =>$resultCode->code,'msg'=>$resultCode->sub_msg]);
        }
        return json_encode($result, JSON_UNESCAPED_UNICODE);

    }


    public function j()
    {
        require_once ROOT_PATH . 'extend/alipay-sdk-PHP-3.3.2/AopSdk.php';
        $ret = alipayEncrypt('123456789012345678901234', '1234567890123456789014');
        dump($ret);
//        $ret2 = alipayDecrypt($ret,'16');
//        dump($ret);
    }


}